package YAPserver.behaviours;

import java.util.Random;

import YAPserver.collisionEngine.*;
import YAPserver.gameObjects.Line;
import YAPserver.gameObjects.Point;
import YAPserver.gameObjects.GameWall;
import YAPserver.logic.Player;

/**
 * This BounceBehaviour is used by the ModBounceToPlayer
 * @author Daniel
 *
 */

public class BounceToPlayer implements BounceBehaviour {
	Player m_player;
	public BounceToPlayer(Player player){
		this.m_player = player;
	}
	@Override
	public void bounce(Ball ball, Wall wall) {
		double speed = ball.getSpeed();
		ball.setSpeed(speed * 2);
		//set speed higher just for fun
		Point q = Collision.intersection(ball, wall);
		double newAngle = calcNewAngle(ball);
		ball.setAngle(newAngle);
		Point radiusVec = new Point(wall.getNormal());
		radiusVec.scalarMult(ball.getRadius());
		ball.setNextMiddlePoint(q.add(radiusVec));
	}
	/**
	 * Calculates a new angle so that the ball is directioned at a specific player's wall. Note that the ball's angle is not changed here.
	 * @param ball ballAbstract whose angle is to be changed.
	 * @return the new angle of the ball
	 */
	private double calcNewAngle(Ball ball) {
		Random rand = new Random();
		
		Point middlePoint = ball.getNextMiddlePoint();
		GameWall wall = m_player.getWall();
		Line line1 = new Line(middlePoint, wall.getStartPoint());
		Line line2 = new Line(middlePoint, wall.getEndPoint());
		double minAngle = line1.getAngle();
		double maxAngle = line2.getAngle();
		double newAngle;
		if(maxAngle < minAngle){
			maxAngle = maxAngle + 2*Math.PI;
		}
		newAngle = minAngle + rand.nextDouble()*(maxAngle-minAngle);
		if(newAngle>2*Math.PI){
			newAngle = newAngle - 2*Math.PI;
		}
		return newAngle;
	}
}
